<template>
  <el-main>
    <el-card>
      <!-- 更新页面标题样式 -->
      <div class="page-header">
        <div class="page-title">二维码管理</div>
        <div class="page-subtitle">设备二维码名片管理</div>
      </div>
      
      <div class="batch-actions">
        <el-button size="small" type="primary" @click="batchDownload">批量下载二维码名片</el-button>
        <el-button size="small" type="success" @click="batchPrint">批量打印二维码名片</el-button>
      </div>
      <div class="device-card-list">
        <div
          v-for="device in devices"
          :key="device.objectId"
          class="device-card"
        >
          <div class="card-title">设备信息</div>
          <div class="card-content">
            <div class="qrcode-box">
              <qrcode-vue :value="getDeviceUrl(device)" :size="80" :id="`qrcode-svg-${device.objectId}`" render-as="canvas" />
            </div>
            <div class="info-box">
              <div>设备名称：{{ device.name }}</div>
              <div>规格型号：{{ device.model }}</div>
              <div>设备编号：{{ device.code }}</div>
              <div>生产厂家：{{ device.manufacturer }}</div>
            </div>
          </div>
          <div class="card-actions">
            <el-button size="small" @click="downloadQRCodeCard(device)">下载二维码</el-button>
            <el-button size="small" @click="printQRCodeCard(device)">打印二维码</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </el-main>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import AV from '../leancloud'
import QrcodeVue from 'qrcode.vue'

// 定义props
const props = defineProps({
  isGuestMode: Boolean
})

const devices = ref([])

const fetchDevices = async () => {
  const query = new AV.Query('Device')
  query.limit(1000)
  const results = await query.find()
  devices.value = results.map(d => d.toJSON())
}
onMounted(fetchDevices)

function getDeviceUrl(device) {
  const ip = '192.168.10.47'
  const port = '5173'
  const token = localStorage.getItem('sessionToken')
  return `http://${ip}:${port}/#/device-detail?id=${device.objectId}${token ? `&token=${token}` : ''}`
}

function downloadQRCode(id) {
  const canvas = document.querySelector(`#qrcode-svg-${id}`)
  if (!canvas) {
    alert('未找到二维码Canvas元素');
    return
  }
  const url = canvas.toDataURL('image/png')
  const a = document.createElement('a')
  a.href = url
  a.download = 'qrcode.png'
  a.click()
}
function printQRCode(id) {
  const svg = document.querySelector(`#qrcode-svg-${id}`)
  if (!svg) return
  const win = window.open('', '_blank')
  win.document.write('<html><head><title>打印二维码</title></head><body style="text-align:center;">')
  win.document.write(svg.outerHTML)
  win.document.write('<br/><button onclick="window.print()">打印</button>')
  win.document.write('</body></html>')
  win.document.close()
}

function drawBeautifulCard(ctx, device, qrCanvas, width, height) {
  // 背景
  ctx.save();
  ctx.shadowColor = 'rgba(58,122,254,0.18)';
  ctx.shadowBlur = 8;
  ctx.beginPath();
  ctx.rect(0, 0, width, height);
  ctx.closePath();
  const grad = ctx.createLinearGradient(0, 0, width, height);
  grad.addColorStop(0, '#f5faff'); grad.addColorStop(1, '#e3eefd');
  ctx.fillStyle = grad;
  ctx.fill();
  ctx.restore();
  // 设备信息色块（紧贴上边缘）
  const infoBarY = 0, infoBarH = 28;
  ctx.save();
  ctx.fillStyle = '#3a7afe';
  ctx.fillRect(0, infoBarY, width, infoBarH);
  ctx.restore();
  // 统一二维码参数
  const qrX = 18, qrY = infoBarY + infoBarH + 14, qrW = 60, qrH = 60, qrR = 6, qrPad = 4;
  // 设备信息四字与二维码水平居中
  ctx.font = 'bold 14px Arial';
  ctx.fillStyle = '#fff';
  ctx.textAlign = 'left';
  const infoTitle = '设备信息';
  const infoTitleWidth = ctx.measureText(infoTitle).width;
  const infoTitleX = qrX + qrW/2 - infoTitleWidth/2;
  ctx.fillText(infoTitle, infoTitleX, infoBarY + infoBarH/2 + 5);
  // 标题下分隔线
  ctx.strokeStyle = '#e3eefd';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(16, infoBarY+infoBarH); ctx.lineTo(width-16, infoBarY+infoBarH);
  ctx.stroke();
  // 二维码灰色圆角边框+白底+留白
  ctx.save();
  ctx.beginPath();
  ctx.moveTo(qrX+qrR, qrY);
  ctx.lineTo(qrX+qrW-qrR, qrY);
  ctx.quadraticCurveTo(qrX+qrW, qrY, qrX+qrW, qrY+qrR);
  ctx.lineTo(qrX+qrW, qrY+qrH-qrR);
  ctx.quadraticCurveTo(qrX+qrW, qrY+qrH, qrX+qrW-qrR, qrY+qrH);
  ctx.lineTo(qrX+qrR, qrY+qrH);
  ctx.quadraticCurveTo(qrX, qrY+qrH, qrX, qrY+qrH-qrR);
  ctx.lineTo(qrX, qrY+qrR);
  ctx.quadraticCurveTo(qrX, qrY, qrX+qrR, qrY);
  ctx.closePath();
  ctx.fillStyle = '#fff';
  ctx.fill();
  ctx.strokeStyle = '#d3d6db';
  ctx.lineWidth = 2;
  ctx.stroke();
  ctx.drawImage(qrCanvas, qrX+qrPad, qrY+qrPad, qrW-2*qrPad, qrH-2*qrPad);
  ctx.restore();
  // 信息区整体适度下移，字体缩小
  ctx.font = '12px Arial';
  ctx.fillStyle = '#222';
  ctx.textAlign = 'left';
  // 右侧：设备名称、规格型号，严格与二维码垂直居中
  const infoX = 90;
  const nameFontSize = 12, lineH = 18;
  ctx.font = nameFontSize + 'px Arial';
  // 让两行文字的中心与二维码中心对齐
  const textBlockHeight = lineH;
  const infoY = qrY + qrH/2 - textBlockHeight/2 + 4;
  ctx.fillText('设备名称：' + (device.name||''), infoX, infoY - 1);
  ctx.fillText('规格型号：' + (device.model||''), infoX, infoY + lineH + 3);
  // 二维码下方：设备编号、生产厂家，整体适度下移
  const underQrX = 18, underQrY = qrY+qrH+22, underLineH = 16, underWidth = width-36;
  ctx.font = '12px Arial';
  ctx.fillStyle = '#222';
  ctx.textAlign = 'left';
  function fillWrapText(text, x, y, maxWidth) {
    const words = text.split('');
    let line = '';
    let lineY = y;
    for(let i=0;i<words.length;i++){
      const testLine = line + words[i];
      const metrics = ctx.measureText(testLine);
      if(metrics.width > maxWidth && line) {
        ctx.fillText(line, x, lineY);
        line = words[i];
        lineY += underLineH;
      } else {
        line = testLine;
      }
    }
    if(line) ctx.fillText(line, x, lineY);
    return lineY;
  }
  ctx.font = '12px Arial';
  let y1 = fillWrapText('设备编号：' + (device.code||''), underQrX, underQrY-2, underWidth);
  fillWrapText('生产厂家：' + (device.manufacturer||''), underQrX, y1+underLineH+2, underWidth);
}

function downloadQRCodeCard(device) {
  const qrCanvas = document.querySelector(`#qrcode-svg-${device.objectId}`)
  if (!qrCanvas) {
    alert('未找到二维码Canvas元素');
    return
  }
  const width = 240, height = 160;
  const card = document.createElement('canvas');
  card.width = width;
  card.height = height;
  const ctx = card.getContext('2d');
  drawBeautifulCard(ctx, device, qrCanvas, width, height);
  const url = card.toDataURL('image/png');
  const a = document.createElement('a');
  a.href = url;
  a.download = `${device.name||'设备'}-二维码名片.png`;
  a.click();
}
function printQRCodeCard(device) {
  const qrCanvas = document.querySelector(`#qrcode-svg-${device.objectId}`)
  if (!qrCanvas) {
    alert('未找到二维码Canvas元素');
    return
  }
  const width = 240, height = 160;
  const card = document.createElement('canvas');
  card.width = width;
  card.height = height;
  const ctx = card.getContext('2d');
  drawBeautifulCard(ctx, device, qrCanvas, width, height);
  const url = card.toDataURL('image/png');
  const win = window.open('', '_blank');
  win.document.write('<html><head><title>打印二维码名片</title></head><body style="text-align:center;"><img src="' + url + '" style="margin:30px auto;display:block;"/><script>window.onload=function(){window.print();window.close();}<' + '/script></body></html>');
  win.document.close();
}

function batchDownload() {
  devices.value.forEach(device => {
    setTimeout(() => downloadQRCodeCard(device), 200);
  });
}
function batchPrint() {
  const cards = [];
  devices.value.forEach(device => {
    const qrCanvas = document.querySelector(`#qrcode-svg-${device.objectId}`)
    if (!qrCanvas) return;
    const width = 240, height = 160;
    const card = document.createElement('canvas');
    card.width = width;
    card.height = height;
    const ctx = card.getContext('2d');
    drawBeautifulCard(ctx, device, qrCanvas, width, height);
    cards.push(card.toDataURL('image/png'));
  });
  let html = '<html><head><title>批量打印二维码名片</title><style>' +
    '@media print { .page-break { display: block; page-break-after: always; } }' +
    '.card-grid { display: flex; flex-wrap: wrap; width: 100%; }' +
    '.card-print { width: 32%; margin: 0.5%; box-sizing: border-box; display: flex; justify-content: center; align-items: center; }' +
    '.card-print img { width: 100%; max-width: 240px; max-height: 160px; border: 1px solid #eee; box-shadow: 0 2px 8px #eee; }' +
    '</style></head><body>';
  for (let i = 0; i < cards.length; i += 9) {
    html += '<div class="card-grid">';
    for (let j = 0; j < 9 && i + j < cards.length; j++) {
      html += '<div class="card-print"><img src="' + cards[i+j] + '" /></div>';
    }
    html += '</div>';
    if (i + 9 < cards.length) html += '<div class="page-break"></div>';
  }
  html += '<script>window.onload=function(){window.print();window.close();}<' + '/script></body></html>';
  const win = window.open('', '_blank');
  win.document.write(html);
  win.document.close();
}
</script>

<style scoped>
/* 页面标题样式 */
.page-header {
  margin-bottom: 20px;
  text-align: center;
}

/* 页面标题样式已移至全局样式文件 */

.device-card-list {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}
.device-card {
  width: 320px;
  border: 2px solid #3a7afe;
  border-radius: 10px;
  background: linear-gradient(135deg, #f5faff 60%, #e3eefd 100%);
  padding: 18px 18px 12px 18px;
  box-shadow: 0 2px 8px 0 rgba(58,122,254,0.08);
  margin-bottom: 12px;
}
.card-title {
  font-size: 20px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 12px;
}
.card-content {
  display: flex;
  align-items: flex-start;
  gap: 18px;
}
.qrcode-box {
  border: 1px solid #888;
  background: #fff;
  padding: 6px;
  border-radius: 6px;
  min-width: 90px;
  min-height: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.info-box {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 15px;
  color: #222;
}
.card-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 10px;
}
.batch-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 18px;
}

/* 统一按钮样式 */
.batch-actions .el-button {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  gap: 6px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.batch-actions .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.batch-actions .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.batch-actions .el-button[type="success"] {
  background: linear-gradient(135deg, #67c23a 0%, #529b2e 100%);
  border: 1px solid #67c23a;
  color: white;
}

.batch-actions .el-button[type="success"]:hover {
  background: linear-gradient(135deg, #529b2e 0%, #3f7c23 100%);
  border-color: #529b2e;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(103, 194, 58, 0.3);
}

.card-actions .el-button {
  font-weight: 600;
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 6px;
  gap: 4px;
  height: 32px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.card-actions .el-button:not([type]) {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  border: 1px solid #dcdfe6;
  color: #606266;
}

.card-actions .el-button:not([type]):hover {
  background: linear-gradient(135deg, #e4e7ed 0%, #d3d7de 100%);
  border-color: #c0c4cc;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 确保按钮内容居中 */
.el-button .el-button__content {
  display: flex;
  justify-content: center;
  align-items: center;
}
@media (max-width: 700px) {
  .el-main {
    padding: 4px !important;
  }
  .page-header {
    text-align: left;
    padding-left: 10px;
    padding-bottom: 5px;
  }
  /* 页面标题样式已移至全局样式文件 */
  .device-card-list {
    flex-direction: column !important;
    gap: 10px !important;
  }
  .device-card {
    width: 100% !important;
    min-width: unset;
    margin-bottom: 10px;
    padding: 10px 6px 8px 6px;
  }
  .el-button, .el-input, .el-select {
    font-size: 16px !important;
    min-height: 38px !important;
  }
}
</style>
